<?php
include "./conn.php";
//PHP端重写
//改进版 格式与文件大小判断
//不定期更新详情关注:https://gitee.com/weivote/phpbigfileUpload
function jsonMsg($code,$msg,$url=''){
  $arr = []; $arr['code'] = $code; $arr['msg'] = $msg; $arr['url'] = $url;
  header('Content-type: application/json');
  exit(json_encode($arr));
}
function heFile($filebath,$bnum)  {
  $wfp = fopen($filebath, $bnum == 1 ? "wb" : "ab");
  $rfp = fopen($_FILES['file']['tmp_name'], "rb");
  $bool = false;
  while ($buff = fread($rfp, 4096)) {
  if(!$bool = fwrite($wfp, $buff)) return $bool;
  }
  fclose($wfp);
  fclose($rfp);
  return $bool;
}

if(!$_FILES['file']['tmp_name'] || !$_POST['blob_num']) exit(date("YmdHis"));
 $filex = $_FILES['file'];
 $filen = (isset($_POST['file_name']))?Trim($_POST['file_name']):'';
 $filea = preg_replace("/[^\x{4e00}-\x{9fa5}^0-9^A-Z^a-z]+/u", '_', $filen);
 $timen = (isset($_POST['nowYmd']))?Trim($_POST['nowYmd']):date("YmdHis");
if ($filex["error"] > 0){
$fer = []; $ercode = $filex["error"];
$fer["1"] = '上传的文件超过了upload_max_filesize选项限制的值';
$fer["2"] = '上传文件的大小超过了表单MAX_FILE_SIZE选项指定的值';
$fer["3"] = '上传异常,文件只有部分被上传';
$fer["4"] = '文件空白或者说没有文件被上传';
$fer["6"] = '上传的临时文件丢失';
$fer["7"] = '文件写入失败建议检查文件夹读写权限';
if($fer[$ercode]){
jsonMsg("0","Error 00".$ercode.":".$fer[$ercode]);
}else{
jsonMsg("0","Error 00".$ercode.":未知上传错误!");
}
}else{
$info = pathinfo($filen); $tape = strtolower($info['extension']);
if(!stristr("|$upext|","|.{$tape}|")){ jsonMsg("0","Error 010,后缀.{$tape}不支持!");}
if($filex["size"]>$dlimi*1024*1024){ jsonMsg("0","Error 011,单片文件大小超{$dlimi}MB!");}
if($_POST["filesize"]>$zlimi*1024*1024){ jsonMsg("0","Error 012,文件总大小超{$zlimi}MB!");}
$filepath = "./upload/$tape/$timen";  //存储路径
if(!is_dir($filepath)) { @mkdir($filepath,0755,true);}
if(!is_dir($filepath)) { jsonMsg("0","Error 015,文件夹失败{$filepath}!");}
$filebath = $filepath . "/". $filen;
$bnum = (isset($_POST['blob_num']))?addslashes($_POST['blob_num']):'';
$tnum = (isset($_POST['total_blob_num']))?addslashes($_POST['total_blob_num']):'';
$fnum = (isset($_POST['filesize']))?addslashes($_POST['filesize']):'0';
if(!is_numeric($bnum) || !is_numeric($tnum)) jsonMsg("0","Error 0161,分片参数得数字!");
if(!is_numeric($fnum) ) jsonMsg("0","Error 0162,参数filesize得数字!");
 $urlx = $ihosts.Ltrim($filebath,".");
if("@$bnum" == "@1" && "@$tnum"=="@1"){
 move_uploaded_file($_FILES['file']['tmp_name'],$filebath);//直接更名保存
 $fsize=filesize($filebath);
 if($fnum==$fsize) jsonMsg("2","OK",$urlx); else jsonMsg("2","可能异常!",$urlx);
}elseif($bnum<$tnum && $tnum>1){
 heFile($filebath,$bnum);
 jsonMsg("1","waiting $bnum/$tnum !");
}elseif($bnum==$tnum && $tnum>1){
 heFile($filebath,$bnum);
 $fsize=filesize($filebath);
 if($fnum==$fsize) jsonMsg("2","OK",$urlx); else jsonMsg("2","可能异常!",$urlx);
}else{
 jsonMsg("0","Error 017,分片异常：$bnum / $tnum!");
}

}